package com.animerank.service.impl;

import com.animerank.mapper.VoteMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.animerank.entity.Anime;
import com.animerank.entity.Favorite;
import com.animerank.mapper.AnimeMapper;
import com.animerank.mapper.FavoriteMapper;
import com.animerank.service.IAnimeService;
import com.animerank.service.IUserActivityService;
import com.animerank.service.IFavoriteService;
import com.animerank.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.dev33.satoken.stp.StpUtil;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 收藏服务实现类
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements IFavoriteService {

    @Autowired
    private AnimeMapper animeMapper;

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private VoteMapper voteMapper;
    
    @Autowired
    private IAnimeService animeService;
    
    @Autowired
    private IUserActivityService userActivityService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> addFavorite(Long animeId) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Result.fail("用户未登录");
        }

        // 检查是否已收藏
        Integer count = favoriteMapper.checkUserFavorite(userId, animeId);
        if (count != null && count > 0) {
            return Result.fail("已经收藏过该动漫");
        }

        // 添加收藏记录
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setAnimeId(animeId);
        favorite.setFavoritedAt(LocalDateTime.now());
        save(favorite);

        // 更新动漫的收藏数量
        animeMapper.incrementFavorites(animeId);
        
        // 获取动漫信息
        Anime anime = animeService.getById(animeId);
        if (anime != null) {
            // 记录用户活动
            userActivityService.recordActivity(userId, "favorite", animeId, anime.getTitle(), null);
        }

        return Result.success("收藏成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> removeFavorite(Long animeId) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Result.fail("用户未登录");
        }

        // 检查是否已收藏
        Integer count = favoriteMapper.checkUserFavorite(userId, animeId);
        if (count == null || count == 0) {
            return Result.fail("未收藏该动漫");
        }

        // 删除收藏记录
        favoriteMapper.deleteByUserIdAndAnimeId(userId, animeId);

        // 更新动漫的收藏数量
        animeMapper.decrementFavorites(animeId);

        return Result.success("取消收藏成功");
    }

    @Override
    public Result<Boolean> checkFavorite(Long animeId) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Result.success(false);
        }

        // 检查是否已收藏
        Integer count = favoriteMapper.checkUserFavorite(userId, animeId);
        return Result.success(count != null && count > 0);
    }

    @Override
    public Result<Map<String, Object>> getUserFavoriteIds(Integer page, Integer pageSize) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Result.success(new HashMap<>());
        }
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        List<Long> favoriteIds = favoriteMapper.getUserFavoriteAnimeIds(userId, offset, pageSize);
        int total = favoriteMapper.countUserFavorites(userId);
        
        // 获取完整的动漫信息
        List<Anime> animeList = new ArrayList<>();
        if (!favoriteIds.isEmpty()) {
            animeList = animeMapper.getAnimesByIds(favoriteIds);
            
            // 确保返回的动漫列表顺序与收藏ID列表顺序一致
            Map<Long, Anime> animeMap = new HashMap<>();
            for (Anime anime : animeList) {
                animeMap.put(anime.getId(), anime);
            }
            
            List<Anime> orderedAnimeList = new ArrayList<>();
            for (Long id : favoriteIds) {
                if (animeMap.containsKey(id)) {
                    Anime anime = animeMap.get(id);
                    Integer voteCount = voteMapper.countAnimeVotes(id);
                    anime.setVotes(voteCount != null ? voteCount : 0);
                    orderedAnimeList.add(anime);
                }
            }
            animeList = orderedAnimeList;
        }

        Map<String, Object> result = new HashMap<>();
        result.put("data", animeList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (int) Math.ceil((double) total / pageSize));
        
        return Result.success(result);
    }

    @Override
    public Result<Integer> getAnimeFavoriteCount(Long animeId) {
        // 统计动漫的收藏数量
        Integer count = favoriteMapper.countAnimeFavorites(animeId);
        return Result.success(count != null ? count : 0);
    }
    
    @Override
    public Result<Map<Long, Boolean>> batchCheckFavorites(List<Long> animeIds) {
        // 验证输入
        if (animeIds == null || animeIds.isEmpty()) {
            return Result.success(new HashMap<>());
        }
        
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        Map<Long, Boolean> resultMap = new HashMap<>();
        
        if (userId == null) {
            // 用户未登录，所有动漫都未收藏
            for (Long animeId : animeIds) {
                resultMap.put(animeId, false);
            }
        } else {
            // 查询用户已收藏的动漫ID
            List<Long> favoritedAnimeIds = favoriteMapper.batchCheckUserFavorites(userId, animeIds);
            Set<Long> favoritedSet = new HashSet<>(favoritedAnimeIds);
            
            // 构建结果映射
            for (Long animeId : animeIds) {
                resultMap.put(animeId, favoritedSet.contains(animeId));
            }
        }
        
        return Result.success(resultMap);
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        if (StpUtil.isLogin()) {
            return StpUtil.getLoginIdAsLong();
        }
        return null;
    }

}